var util = require('../../utils/util.js');
var api = require('../../config/api.js');
 
function initSubMenuDisplay() {
  return ['hidden', 'hidden', 'hidden']; //searchByCondition
}
function initArrows(){
  return ['down-triangle', 'down-triangle','down-triangle'];
}
function menuFontColor(){
  return ['','',''];
} 
 
//声明初始化高亮状态数组
function initSubMenuHighLight() {
  return [['', '', '', '', ''], ['', ''], ['', '', '']];
}

//定义初始化数据，用于运行时保存
var initSubMenuHighLight = [
  ['', '', '', '', ''],
  ['', ''],
  ['', '', '']
];

//定义查询条件数组，保存查询条件
var queryConditionArr = ['','',''];
//声明星级或销量排序项
// function starSales(){
//   return ['price', 'sellNum', 'likeNum', 'wantGoNum', 'favoriteNum', 'startAt', 'endAt'];
// }
function getStarSalesArray(){
  return [{
    "id": 0,
    "EN": "customerPrice",
    "CN": "价格",
    "def_sort": "desc",
    "curr_sort": "no",
    "curr_discription": "",
    "sort_discription": { "desc": "高->低", "asc": "低->高" }
  }, {
    "id": 1,
    "EN": "sellNum",
    "CN": "销量",
    "def_sort": "desc",
    "curr_sort": "no",
    "curr_discription": "",
    "sort_discription": { "desc": "高->低", "asc": "低->高" }
  }, {
    "id": 2,
    "EN": "likeNum",
    "CN": "点赞",
    "def_sort": "desc",
    "curr_sort": "no",
    "curr_discription": "",
    "sort_discription": { "desc": "高->低", "asc": "低->高" }
  }, {
    "id": 3,
    "EN": "wantGoNum",
    "CN": "想去",
    "def_sort": "desc",
    "curr_sort": "no",
    "curr_discription": "",
    "sort_discription": { "desc": "高->低", "asc": "低->高" }
  }, {
    "id": 4,
    "EN": "favoriteNum",
    "CN": "收藏",
    "def_sort": "desc",
    "curr_sort": "no",
    "curr_discription": "",
    "sort_discription": { "desc": "高->低", "asc": "低->高" }
  }, {
    "id": 5,
    "EN": "startAt",
    "CN": "时间",
    "def_sort": "asc",
    "curr_sort": "no",
    "curr_discription": "",
    "sort_discription": { "desc": "晚->早", "asc": "早->晚" }
  },{
    "id": 6,
    "EN": "day",
    "CN": "行程",
    "def_sort": "asc",
    "curr_sort": "no",
    "curr_discription": "",
    "sort_discription": { "desc": "长->短", "asc": "短->长" }
  }
  ];
}


//暂存星级销量排序
var sortTmp = [];
var selectSort = {
  ename:'',
  currsort:''
};
//活动类别显示控制
var showActIndex = ["0","1","4"];
var showStarIndex = ["0","1","5","6"];

//出行方式控制
var traveltypes = [
                    { id: '', fullName: '出行方式' },
                    { id: '1', fullName:'出行方式-游轮'},
                    { id: '2', fullName: '出行方式-飞机' },
                    { id: '3', fullName: '出行方式-大巴' },
                    { id: '4', fullName: '出行方式-火车' },
                    { id: '5', fullName: '出行方式-高铁' }
                 ]
Page({
   
  data: {
    searchTxt:'点击搜索目的地/关键词',
    subMenuDisplay: initSubMenuDisplay(),
    subMenuArrows: initArrows(),
    locationInfo:'目的地',
    locationInfos: ['目的地'],//['上海', '西安', '全部'],
    campaignTypeInfo: '活动类别',
    //campaignTypeInfos: initActivityStyle(),//['户外', '景区', '团建', '亲子', '自驾', '定制'],
    campaignTypeInfos: [{"fullName":'全部',"id":""}],

    travelTypeInfo: '出行方式',
    travelTypeInfos: traveltypes,

    moreInfo: '星级/销量',
    moreInfos: [],
    city: '上海市',
    county: '徐汇区',
    typeId: '', 
    key: null,
    images: '',
    title: '',
    location: '',
    grade:'',
    price : '',
    arrow: 'down-triangle',
    fontlight:'',
    showBottom: true,
    loadMoreData: '~到底了喔~',
    xl_hs:0,
    isrecommend:false,
    discrption : "抱歉，没找到对应活动，为您推荐以下活动",
    cityMaxLen:220
  },
  tapMainMenu: function (e) {//        获取当前显示的一级菜单标识
    var index = parseInt(e.currentTarget.dataset.index);        // 生成数组，全为hidden的，只对当前的进行显示
    var newSubMenuDisplay = initSubMenuDisplay();//        如果目前是显示则隐藏，反之亦反之。同时要隐藏其他的菜单
    var newinitArrows = initArrows();
    if (this.data.subMenuDisplay[index] == 'hidden') {
      newSubMenuDisplay[index] = 'show';
      
    } else {
      newSubMenuDisplay[index] = 'hidden';
    }        // 设置为新的数组
    if (this.data.subMenuArrows[index] == 'down-triangle'){
      newinitArrows[index] = 'up-triangle';
    }else{
      newinitArrows[index] = 'down-triangle';
    }

    this.setData({
      /*yzp-s*/
      /*
      locationInfo:'位置区域',
      campaignTypeInfo: '活动类别',
      moreInfo: '星级/销量',
      */
      /*yzp-e*/
      subMenuDisplay: newSubMenuDisplay,
      subMenuArrows: newinitArrows,
      sortitem: sortTmp
    });
  },
  //获取当前显示的一级菜单标识
  // tapSubMenu: function (e) {
  //   var index = parseInt(e.currentTarget.dataset.index);
  //   console.log(index);  // 隐藏所有一级菜单
  //   this.setData({
  //     subMenuDisplay: initSubMenuDisplay()
  //   });
  // },
  tapSubMenu: function (e) {        // 隐藏所有一级菜单

    var that = this;

    this.setData({
      subMenuDisplay: initSubMenuDisplay()
    });        // 处理二级菜单，首先获取当前显示的二级菜单标识
    var indexArray = e.currentTarget.dataset.index.split('-');        // 初始化状态

    /*yzp-s*/

    var i0 = parseInt(indexArray[0]);
    var i1 = parseInt(indexArray[1]);
 
    if(i0 == 0){

      this.setData({
        locationInfo: e.target.dataset.text
      });  

      var jsonO = { "campaignName": e.target.dataset.text};
      queryConditionArr[0] = jsonO;
      if (e.target.dataset.text == '目的地') {
        queryConditionArr[0] = {}
      } else if (e.target.dataset.text.indexOf('目的地-')==0){
        queryConditionArr[0].campaignName = e.target.dataset.text.substring(4, e.target.dataset.text.length)
      } 
        
      
    }else if(i0 == 1){
      // this.setData({
      //   campaignTypeInfo: e.target.dataset.text
      // }); 

      this.setData({
        travelTypeInfo: e.target.dataset.text
      }); 

      if (typeof (i1) == "number") {
        var jsonO = { "travelType": Number(i1) + 1 + "" };
        queryConditionArr[1] = jsonO;
        if (e.target.dataset.text == '出行方式') {
          queryConditionArr[1] = {}
        }
        // this.queryAndOrderByManyConditions(queryConditionArr);
      }
    } else if (i0 == 2) {
      
      var starArray = this.getStarAndSale();
      //获取当前选中状态
      var currsort = e.currentTarget.dataset.sort;
      var enName = e.currentTarget.dataset.item.EN;
      selectSort.ename = enName;
      selectSort.currsort = currsort;

      var newArray = starArray.map(function (item, index) {
        if (selectSort.ename == item.EN) {
          
          //no->def  desc->asc asc->desc
          if ("no" == selectSort.currsort) {
            item.curr_sort = item.def_sort;
          } else if ("desc" == selectSort.currsort) {
            item.curr_sort = "asc";
          } else if ("asc" == selectSort.currsort) {
            item.curr_sort = "desc";
          }

          selectSort.currsort = item.curr_sort;
          item.curr_discription = item.sort_discription[selectSort.currsort];
          that.setData({
            moreInfo: item.CN + item.curr_discription
          });
        }
        return item;
      });
      that.setData({
        moreInfos: newArray
      });
     
      var jsonO = { [enName]: selectSort.currsort };
      queryConditionArr[2] = jsonO;
    }
    //查询数据
    this.queryAndOrderByManyConditions(queryConditionArr);
    

    /*yzp-e*/
    // var newSubMenuHighLight = initSubMenuHighLight;
    for (var i = 0; i < initSubMenuHighLight.length; i++) {            // 如果点中的是一级菜单，则先清空状态，即非高亮模式，然后再高亮点中的二级菜单；如果不是当前菜单，而不理会。经过这样处理就能保留其他菜单的高亮状态
      if (indexArray[0] == i) {
        for (var j = 0; j < initSubMenuHighLight[i].length; j++) {                    // 实现清空
          initSubMenuHighLight[i][j] = '';
        }                // 将当前菜单的二级菜单设置回去
      }
    }        // 与一级菜单不同，这里不需要判断当前状态，只需要点击就给class赋予highlight即可
    initSubMenuHighLight[indexArray[0]][indexArray[1]] = 'highlight';        // 设置为新的数组
    this.setData({
      subMenuHighLight: initSubMenuHighLight,
      subMenuArrows: initArrows()
    });
  },
  todetail:function(e){
    var id = e.currentTarget.dataset.index;
    getApp().globalData.currentGoodsId = id;
    wx.navigateTo({
      url: '/pages/goods/goods?id='+id
    })
  },
  toSearch:function(e){
    wx.redirectTo({
      url: '/pages/search/search?keyword=' + this.data.searchTxt
    })
  },
  onLoad: function (options){

    console.log('参数',options)

    if (options.typeId){
      this.setData({
        typeId: options.typeId,
        campaignTypeInfo : options.fullName,
        fontstatus:1
      });
      // 动态改变页面标题
      wx.setNavigationBarTitle({
        title: options.fullName
      })
      this.getActivityListByTypeId();
    } else if (options.type == 'BANNER' && getApp().globalData.bannerGoodLists.length >0){
      //获取Banner 商品
     var  bannerGoodLists = getApp().globalData.bannerGoodLists

      console.log(bannerGoodLists)
      
      //从banner和搜索进入列表页，无法取到活动分类，依靠返回的第一个活动的分类作为整体的分类
      var restype = bannerGoodLists.length >= 1 ? bannerGoodLists[0].type ? bannerGoodLists[0].type : 1 : 1
      var res_goodslist = bannerGoodLists.filter(item=>item.type == restype)

      this.setData({
        activityList: res_goodslist,
        key: res_goodslist,
        typeId: restype
      })

      if(options.key == "icon1"){
        this.setData({
          searchTxt:'人气排行榜'
        });
      } else if (options.key == "icon2"){
        this.setData({
          searchTxt: '热门促销'
        });
      }
    } else if (options.type == 'SEARCH' && getApp().globalData.searchGoodInfo.campaignList.length > 0){
      this.setListInfo(options.keyword);
    }else{
      this.getAllActivityList()
    }

    // this.getActivityClassify();
    this.GetCityList();
    this.setData({
      moreInfos: this.getStarAndSale()
    });

    

  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function (options) {

  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  getCurrentType:function(){
    let that = this;
    var arr = this.data.campaignTypeInfos
    var tid = this.data.typeId;
    arr.map(function(item){

        if(item.id == tid){
          that.setData({
            campaignTypeInfo: item.fullName,
            fontstatus: 1
          })
        }
        console.log(item)

    })
  },
  setListInfo: function (options){
    var that = this;
    var info = getApp().globalData.searchGoodInfo
    console.log("搜索返回列表",info)

    //从banner和搜索进入列表页，无法取到活动分类，依靠返回的第一个活动的分类作为整体的分类
    var restype = info.campaignList.length >= 1 ? info.campaignList[0].type ? info.campaignList[0].type : 1 : 1
    var res_goodslist = info.campaignList.filter(item => item.type == restype)

    that.setData({
        searchTxt: options,
        isrecommend: info.isRecommend,
        activityList: res_goodslist,
        key: res_goodslist,
        typeId: restype
    });
   
  },
  getList: function () {
    var that = this;
    util.request(api.ApiRootUrl + 'api/catalog/' + that.data.currentCategory.cat_id)
      .then(function (res) {
        that.setData({
          categoryList: res.data,
        });
      });
  },

  //根据类型id 获取 改分类下的活动
  getActivityListByTypeId: function (){
    let that = this;
    util.request(api.findgoodlist, { type: that.data.typeId , bizType:1}, 'POST').then(function (res) {
      if (res.responseBody.campaignList){
        that.setData({
          isrecommend: true,
        });
      }else {
        that.setData({
          isrecommend: false,
        });
      }
      that.setData({
        activityList: res.responseBody.campaignList,
        key: res.responseBody.campaignList
      })
      console.log(res.responseBody.campaignList)
    })
  },

  //按照活动类型查
  orderByType: function (typeId) {
    let that = this;
    util.request(api.ActivityUrl, { type: typeId },"GET").then(function (res) {
      that.setData({
        activityList: res.campaignList,
        key: res.campaignList
      })
      console.log(res.campaignList)
    })
  },

  //按星级/销量排序
  orderByMoreType: function (key,value) {
    let that = this;
    var stringJson = '{"' + key + '": "'+ value +'"}';
    var jsonO = JSON.parse(stringJson);
    util.request(api.ActivityUrl, jsonO,"GET").then(function (res) {
      that.setData({
        activityList: res.campaignList,
        key: res.campaignList
      })
      console.log(res.campaignList)
    })
  },

  //多条件查询及排序
  queryAndOrderByManyConditions: function (condition) {
    let that = this;
    // var s = null;
    var s0 = condition[0] == "" ? {} : condition[0] 
    var s1 = condition[1] == "" ? {} : condition[1]
    var s2 = condition[2] == "" ? {} : condition[2]
 
    //合并json 请求参数
    var datatmp = util.mergeJson(s0,s1)
    var data = util.mergeJson(datatmp, s2)
    
    //活动类型必传
    data.type = that.data.typeId;
    data.bizType = 2;
 
    console.log("筛选请求参数：")
    console.log(data)
    util.request(api.findgoodlist, data,'POST').then(function (res) {
      if (res.campaignList) {
        that.setData({
          isrecommend: true,
        });
      }else{
        that.setData({
          isrecommend: false,
        });
      }
      that.setData({
        activityList: res.campaignList,
        key: res.campaignList,
        fontstatus: 1
      });
      
      console.log(res.responseBody);
    });
  },

  //菜单tab 获取 分类
  getActivityClassify: function getActivityClassify() {
    var that = this;
    util.request(api.ActivityClassify).then(function (res) {
      if (res.code == 200) {
        var tmplist = res.responseBody;
        var iconList = [];
        for (var index in tmplist) {
          var icon = {};
          icon.fullName = tmplist[index].fullName;
          icon.imgUrl = tmplist[index].imgUrl;
          icon.id = tmplist[index].id;
          if (showActIndex.indexOf(index)>-1){
            iconList.push(icon);
          }
        }
        var newcampaignTypeInfos = that.data.campaignTypeInfos.concat(iconList)
        that.setData({
          campaignTypeInfos: newcampaignTypeInfos
        });
      }
    })
    // .then(res=>{

    //   that.getCurrentType()
    // });
  },

  //
  getStarAndSale: function getStarAndSale(){
    var that = this;
    var StarAndSales = [];
    var starsales = getStarSalesArray();
    for (var index in showStarIndex){
        var StarAndSale = {};
        StarAndSale = starsales[showStarIndex[index]];
        StarAndSales.push(StarAndSale);
    }
    return StarAndSales;
  },
  En2ch: function En2ch() {
    var that = this;
    that.setData({
      en2ch: {
        price: '价格',
        sellNum: '销量',
        likeNum: '点赞',
        wantGoNum: '想去',
        favoriteNum: '收藏',
        startAt: '开始',
        endAt: '结束'
      }
    });
  },
  GetSortStr: function getSortStr(cuursort,def_sort){
    var that = this;
    var condition = '';
    if ("no" == cuursort){
      condition = def_sort; 
    } else if ("desc" == cuursort){
      condition = "asc";
    }else{
      condition = "desc";
    }
    return condition;
  },
  GetCityList: function(){
    var that = this;
    util.request(api.CityList + "/" + that.data.typeId).then(function (res) {
      if (res.code == 200) {
        var newlocationInfos = that.data.locationInfos.concat(res.responseBody)
        
        var locationInfoArrMap = []

        //为满足列表页的筛选项都加目的地，和城市宽度自适应
        var max=0
        newlocationInfos.forEach(function(item,index,arr){

          var locationInfo = {}

          if (item.length > max) max = item.length
          var memo=''
          if(index==0){
            memo=''
          }else{
            memo='目的地-'
          }
          locationInfo.data = item
          locationInfo.memo = memo

          locationInfoArrMap.push(locationInfo)

        })


        var xl_h = newlocationInfos.length;
        if (xl_h==0){
            that.setData({
              xl_hs: 1
            });
        } else if(0<xl_h && xl_h<= 5){
            that.setData({
              xl_hs: xl_h
            });
        } else if(xl_h>5){
            that.setData({
              xl_hs: 5
            });
          }

          that.setData({
            locationInfos: newlocationInfos,
            cityMaxLen: that.data.cityMaxLen + (max-3)*25 ,// 城市自适应
            locationInfoArrMap: locationInfoArrMap
          });
      }
    });
  },
  getAllActivityList:function(){
      let that =this;
      util.request(api.ActivityUrl, {bizType:1}, 'GET').then(function (res) {
        that.setData({
          activityList: res.campaignList,
          key: res.campaignList
        });
      })
    }
});

